package Service;

import DAO.UserDAO;
import DATA.User;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

@WebServlet(name = "login", urlPatterns = "/login")
public class Login extends HttpServlet {
    @Override
    public void init() throws ServletException {
        super.init();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //找有没有名字
        try {
            User ans = UserDAO.FindbyName(username);
            if (ans != null) {
                //密码对得上就登陆
                if (password.equals(ans.getUserpwd())) {
                    resp.getWriter().write("登录成功");
                    HttpSession session = req.getSession();
                    Cookie cookie = new Cookie("JSESSIONID", session.getId());
                    cookie.setMaxAge(60*60*1);//登陆状态保留一小时
                    cookie.setPath("/");
                    resp.addCookie(cookie);
                    req.getSession().setAttribute("user", username);
                    req.getSession().setAttribute("uid", ans.getId());
                    req.getSession().setAttribute("Email", ans.getEmail());//把邮箱也一并存了吧,方便获取
                } else {
                    //提示出错,其实建议用alert，这样不用返回登陆页面
                    resp.getWriter().write("账号或密码错误");

                }
            } else {
                //提示出错,其实建议用alert，这样不用返回登陆页面
                resp.getWriter().write("不好意思，没找到用户名");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
